package com.toocms.tab.expand.advert;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.toocms.tab.base.BaseActivity;
import com.toocms.tab.binding.command.BindingConsumer;
import com.toocms.tab.expand.R;
import com.toocms.tab.network.ApiTool;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;

/**
 * @Description: 广告页
 * @Author: Zero
 * @CreateDate: 2022/1/8 16:29
 * @UpdateUser:
 * @UpdateDate: 2022/1/8 16:29
 * @UpdateRemark:
 * @Version: 6.1.4
 */
public abstract class BaseAdvertActivity extends BaseActivity {

    /**
     * 默认广告持续时间（倒计时时长）
     */
    private static final long DEFAULT_ADVERT_DURATION_MILLIS = 3500;

    protected QMUIAlphaTextView tvJump;
    protected ImageView imgvAdvert;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_layout_advert);
        initView();
        onActivityCreated();
    }

    private void initView() {
        tvJump = findViewById(R.id.tv_jump);
        tvJump.setOnClickListener(v -> {
            timer.cancel();
            onJumpClickOrFinish();
        });
        imgvAdvert = findViewById(R.id.imgv_advert);
        imgvAdvert.setScaleType(getScaleType());
        imgvAdvert.setOnClickListener(v -> onAdvertClick());
    }

    protected <T> void getAdvert(String url, Class<T> cls, BindingConsumer<T> onSuccess) {
        ApiTool.post(url)
                .asTooCMSResponse(cls)
                .observeOn(AndroidSchedulers.mainThread())
                .request(advert -> {
                    onSuccess.call(advert);
                    timer.start();
                });
    }

    /**
     * activity启动后的初始化
     */
    protected abstract void onActivityCreated();

    /**
     * 跳过/倒计时完毕监听
     */
    protected abstract void onJumpClickOrFinish();

    /**
     * 广告点击监听
     */
    protected abstract void onAdvertClick();

    /**
     * @return 广告持续时间（倒计时时长）
     */
    protected long getAdvertDurationMillis() {
        return DEFAULT_ADVERT_DURATION_MILLIS;
    }

    /**
     * @return 图片裁剪方式
     */
    protected ImageView.ScaleType getScaleType() {
        return ImageView.ScaleType.FIT_XY;
    }

    /**
     * 倒计时
     */
    protected CountDownTimer timer = new CountDownTimer(getAdvertDurationMillis(), 1000) {

        @Override
        public void onTick(long l) {
            tvJump.setText(l / 1000 + "s 跳过");
        }

        @Override
        public void onFinish() {
            onJumpClickOrFinish();
        }
    };
}
